qui(
    function (require, exports, module) {
        VODNew.MaskManager = (function () {
            var _initOver = false;
            var _options = {};
            var Sys = {};

            Sys.Data = {
                index: 0,
                entityIdIndex: 1
            };
            Sys.Config = {
                CropInstance: null,
                isStart: false,
                selectMode: false,
                bindDiv: null,
                gridTarget: null,
                curImageId: -1
            };

            Sys.Util = {
                doCropRelease: function () {
                    console.log("doCropRelease ");
                    Sys.Util.clearBindDiv();
                    $(".maskSelected").removeClass("maskSelected");
                    if ($(".maskSelected").length > 0) {
                        var maskChild = $($(".maskSelected")[0]);
                        if (maskChild.width() < 25 || maskChild.height() < 25) {
                            maskChild.remove();
                        }
                    }
                },
                doCropSelect: function (obj) {
                    //   var showObj = {x: obj.x, y: obj.y, w: obj.w, h: obj.h};
                    var showRect = Sys.Config.CropInstance.tellScaled();
                    var actualRect = Sys.Config.CropInstance.tellSelect();
                    console.log("doCropSelect ", JSON.stringify(showRect), JSON.stringify(actualRect));
                    if (Sys.Config.selectMode) {
                        return;
                    }
                    var maskChild = null;
                    if ($(".maskSelected").length > 0) {
                        maskChild = $($(".maskSelected")[0]);
                        maskChild.css({width: showRect.w, height: showRect.h, "left": showRect.x, "top": showRect.y});
                        maskChild.data("actualRect", $.extend({}, actualRect));
                        maskChild.data("showRect", $.extend({}, showRect));
                        return;
                    } else {
                        maskChild = Sys.Config.bindDiv;
                    }

                    if (maskChild == null) {
                        Sys.Data.index++;
                        var maskChild = Sys.Util.createMaskChild(Sys.Data.index);
                        maskChild.appendTo(_options.maskDivTarget);
                    } else {
                        Sys.Util.clearBindDiv();
                    }
                    Sys.Config.CropInstance.release();
                    maskChild.css({width: showRect.w, height: showRect.h, "left": showRect.x, "top": showRect.y});
                    maskChild.data("actualRect", $.extend({}, actualRect));
                    maskChild.data("showRect", $.extend({}, showRect));
                },
                createMaskChild: function (index) {
                    var maskChild = $('<div><span onclick="VODNew.MaskManager.delegateDelResource(event)" data-id="' + index + '">X</span></div>');
                    maskChild.addClass("maskChild");
                    maskChild.attr("id", "maskChild_" + index);
                    return maskChild;
                },
                clearBindDiv: function () {
                    if (Sys.Config.bindDiv != null) {
                        Sys.Config.bindDiv.show();
                        Sys.Config.bindDiv = null;
                        console.log("Sys.Config.bindDiv clear ");
                    }
                },
                delResource: function (event) {
                    console.log("delResource ", event.target);
                    event.stopPropagation();
                    console.log("delResource end");
                    $(event.target).parent().remove();
                    Sys.Config.CropInstance.release();
                }
            };

            function initManager(options) {
                if (_initOver) {
                    console.log("has init over")
                    return;
                }
                _options = options;
                _options.btn_ok.on("click", function (e) {
                    recordMaskObjPos()
                    _options.dlgTarget.dialog("close");
                })
                _options.btn_cancel.on("click", function (e) {
                    _options.dlgTarget.dialog("close");
                });
                _options.btn_preview.on("click", function (e) {
                    doMaskPreview();
                });

                Sys.Config.CropInstance = $.Jcrop("#" + _options.imageTarget.attr("id"), {
                    onRelease: Sys.Util.doCropRelease,
                    onSelect: Sys.Util.doCropSelect,
                    boxHeight: 603,
                    minSelect: [25, 25]
                })

                _options.maskDivTarget.on("click", "div.maskChild", function (event) {
                    console.log("div.maskChild");
                    if (event.target != event.currentTarget) {
                        return false;
                    }
                    Sys.Util.clearBindDiv();
                    var maskChild = $(event.target);
                    var recordRect = maskChild.data("actualRect");
                    var newRect = [ recordRect.x, recordRect.y , recordRect.w, recordRect.h];
                    Sys.Config.selectMode = true;
                    Sys.Config.CropInstance.setSelect([newRect[0], newRect[1], newRect[0] + newRect[2], newRect[1] + newRect[3]  ]);
                    Sys.Config.selectMode = false;
                    Sys.Config.bindDiv = maskChild;
                    Sys.Config.bindDiv.hide();
                    return false
                })
            }

            function delegateDelResource(event) {
                Sys.Util.delResource(event);
            }

            function getPageBean() {
                return  VODNew.Config.PageBeanMaskEntity
            }

            function updateGrid() {
                VODNew.Util.updateGridMaskEntity()
            }

            function addMaskEntity() {
                var entity = createEntity();
                getPageBean().addNewOne(entity);
                updateGrid();
                $("#mask_list").jqGrid('setSelection', entity.index);
                VODNew.Util.setMaskHighLight(null);
            }

            function clearMaskEntity() {
                getPageBean().setNewData([]);
                updateGrid();
                VODCom.NewsHighlight.clearMaskMark();
            }

            function readMaskEntity() {
                var selRow = _options.gridTarget.jqGrid("getGridParam", "selrow");
                var findData = getPageBean().findData("index", selRow);
                if (findData.coverArr.length > 0) {
                    var maskChild = null;
                    $.each(findData.coverArr, function (i, element) {
                        maskChild = Sys.Util.createMaskChild(element.index);
                        maskChild.appendTo(_options.maskDivTarget);
                        maskChild.css({width: element.showRect.w, height: element.showRect.h, "left": element.showRect.x, "top": element.showRect.y});
                        maskChild.data("actualRect", $.extend({}, element.actualRect));
                        maskChild.data("showRect", $.extend({}, element.showRect));
                    })
                }
            }

            function createEntity() {
                var newId = Sys.Data.entityIdIndex;
                Sys.Data.entityIdIndex++;
                return  {
                    index: newId,
                    sTime: -1,
                    eTime: -1,
                    coverArr: []
                }
            }

            function delMaskEntity(rowId) {
                var findData = getPageBean().findData("index", rowId);
                if (findData != null) {
                    getPageBean().delOne(findData);
                    VODCom.NewsHighlight.clearMaskSingleMark(findData.index)
                    updateGrid();
                }
            }

            function modifyMaskEntity(index) {
                var selRow = _options.gridTarget.jqGrid("getGridParam", "selrow");
                console.log("selRow" + selRow);
                if (selRow == null) {
                    return;
                }
                var maskEntity = null;
                if (index != null) {
                    var maskEntity = getPageBean().findData("index", index);
                    if (maskEntity != null && maskEntity.sTime >= 0) {
                        VODNew.Util.doMaskImage(maskEntity.sTime);
                    }
                } else {
                    maskEntity = getPageBean().findData("index", parseInt(selRow));
                    var imageId = parseInt($(".red").parent().find(".pid").html());
                    if (maskEntity.sTime >= 0 && maskEntity.sTime <= imageId) {
                        VODNew.Util.doMaskImage(imageId)
                    }
                }
            }

            function getSelectMaskEntity() {
                var selRow = _options.gridTarget.jqGrid("getGridParam", "selrow");
                if (selRow == null) {
                    return null;
                }
                return  getPageBean().findData("index", parseInt(selRow));
            }

            function doMaskPreview() {
                if (Sys.Config.curImageId == -1) {
                    console.log(" doMaskPreview fail")
                    return;
                }
                var coverArr = makeUpCoverArr();
                var subArr = [];
                $.each(coverArr, function (i, element) {
                    subArr.push(
                        {
                            x: parseInt(element.actualRect.x),
                            y: parseInt(element.actualRect.y),
                            w: Math.ceil(element.actualRect.w),
                            h: Math.ceil(element.actualRect.h)
                        }
                    )
                })
                var sendData = {
                    //  image_id: Sys.Config.curImageId,
                    //     channel_code: paramsData.channel_name,
                    from_client: true,
                    key: VODNew.Dao.settings.taskid,
                    delogo: JSON.stringify(subArr)
                };
                $("#navMaskDiv").tabs({active: 1})
//                $("#demoImg").attr("src", "img/demo_test.jpg")
                VODNew.Dao.getMaskResult(sendData, function (rdata) {
                    if (rdata != null && rdata.code == "A00000") {
                        $("#demoImg").attr("src", rdata.uri + "?t=" + Math.random());
                        console.log("getMaskResult suc" + JSON.stringify(rdata));
                    } else {
                        console.log("getMaskResult fail")
                    }
                })
            }

            function recordMaskObjPos() {
                var maskEntity = getSelectMaskEntity();
                maskEntity.coverArr = makeUpCoverArr();
            }

            function makeUpCoverArr() {
                var retVal = [];
                var childArr = _options.maskDivTarget.children();
                $.each(childArr, function (i, element) {
                    retVal.push({
                            actualRect: $(element).data("actualRect"),
                            showRect: $(element).data("showRect"),
                            index: parseInt($(element).attr("id").replace("maskChild_", ""))
                        }
                    )
                })
                return retVal;
            }

            function makeUpSubDelogoArr() {
                var source = getPageBean().getSource();
//maskJson: [{st,et,coverArr:[{x,y,w,h}]},]
                var subArr = [];
                var singleData = null;
                $.each(source, function (i, single) {
                    singleData = { st: single.sTime, et: single.eTime, coverArr: []};
                    $.each(single.coverArr, function (i, element) {
                        singleData.coverArr.push(
                            {
                                x: parseInt(element.actualRect.x),
                                y: parseInt(element.actualRect.y),
                                w: Math.ceil(element.actualRect.w),
                                h: Math.ceil(element.actualRect.h)
                            }
                        )
                    })
                    subArr.push(singleData);
                })
                return subArr
            }

            function isValidDelogo(source) {
                var isValid = true;
                $.each(source, function (i, single) {
                    if (single.sTime > single.eTime || single.eTime < 0 || single.sTime < 0) {
                        isValid = false;
                        return false
                    }
                })
                return isValid;
            }

            function startWork(showImageId) {
                _options.dlgTarget.dialog("open");
                _options.maskDivTarget.html("");
                $("#navMaskDiv").tabs({active: 0});
                $("#demoImgDiv").css({width: 900, height: 600});
                $("#demoImg").attr("src", "");
                var imageId = showImageId;
                if (imageId == null) {
                    return;
                }
                var paramsData = VODNew.Dao.getParamsData();
                var data = {
                    image_id: imageId,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: VODNew.Dao.settings.taskid
                };
                VODNew.Dao.getOcrImage(data, function (rdata) {//
                    if (rdata != null && rdata.code == "A00000") {
                        var tempHandler = function (rdata2) {
                            Sys.Config.curImageId = -1;
                            if (rdata2 != null && rdata2.code == "A00000") {
                                Sys.Config.curImageId = imageId;
                                Sys.Config.CropInstance.setImage(rdata2.uri);
                                _options.maskDivTarget.html("");
                                readMaskEntity();
                                console.log("startWork doMaskImage suc")
                            } else {
                                VODNew.Plugin.tips("error", VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL);
                                VODNew.Util.logSubmit(VODNew.Config.VOD_LOG_TYPE.getImageData, data, {error: VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL}, VODNew.Dao.getDotData().findImage);
                                VODNew.Util.notifyAlert(VODNew.Config.REMIND_MSG_INFO.GET_IMG_FAIL + ";" + VODNew.Dao.getDotData().ocrimage + "|" + JSON.stringify(data).replace(/"/g, ""));
                            }
                        }
                        if (VODNew.Config.READ_IMAGE_METHOD == "new") {
                            VODNew.Dao.doFindImage("mask_image", data, tempHandler)
                        } else {
                            tempHandler(rdata);
                        }
                    } else {
                        VODNew.Plugin.tips("error", "请求图片失败!");
                    }
                });
            }
            //  function remove
            return {
                initManager: initManager,
                addMaskEntity: addMaskEntity,
                clearMaskEntity: clearMaskEntity,
                delMaskEntity: delMaskEntity,
                modifyMaskEntity: modifyMaskEntity,
                getSelectMaskEntity: getSelectMaskEntity,
                startWork: startWork,
                recordMaskObjPos: recordMaskObjPos,
                isValidDelogo: isValidDelogo,
                makeUpSubDelogoArr: makeUpSubDelogoArr,
                delegateDelResource: delegateDelResource
            }
        })()
    }
);